package com.atguigu.linkedlist;

public class Josepfu {

	public static void main(String[] args) {
		// һѿͱǷok
		CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
		circleSingleLinkedList.addBoy(125);// 5Сڵ
		circleSingleLinkedList.showBoy();
		
		//һСȦǷȷ
		circleSingleLinkedList.countBoy(10, 20, 125); // 2->4->1->5->3
		//String str = "7*2*2-5+1-5+3-3";
	}

}

// һεĵ
class CircleSingleLinkedList {
	// һfirstڵ,ǰûб
	private Boy first = null;

	// Сڵ㣬һε
	public void addBoy(int nums) {
		// nums һУ
		if (nums < 1) {
			System.out.println("numsֵȷ");
			return;
		}
		Boy curBoy = null; // ָ룬
		// ʹforǵĻ
		for (int i = 1; i <= nums; i++) {
			// ݱţСڵ
			Boy boy = new Boy(i);
			// ǵһС
			if (i == 1) {
				first = boy;
				first.setNext(first); // ɻ
				curBoy = first; // curBoyָһС
			} else {
				curBoy.setNext(boy);//
				boy.setNext(first);//
				curBoy = boy;
			}
		}
	}

	// ǰĻ
	public void showBoy() {
		// жǷΪ
		if (first == null) {
			System.out.println("ûκС~~");
			return;
		}
		// ΪfirstܶȻʹһָɱ
		Boy curBoy = first;
		while (true) {
			System.out.printf("Сı %d \n", curBoy.getNo());
			if (curBoy.getNext() == first) {// ˵Ѿ
				break;
			}
			curBoy = curBoy.getNext(); // curBoy
		}
	}

	// û룬СȦ˳
	/**
	 * 
	 * @param startNo
	 *            ʾӵڼСʼ
	 * @param countNum
	 *            ʾ
	 * @param nums
	 *            ʾжСȦ
	 */
	public void countBoy(int startNo, int countNum, int nums) {
		// ȶݽУ
		if (first == null || startNo < 1 || startNo > nums) {
			System.out.println(" ");
			return;
		}
		// Ҫָ,СȦ
		Boy helper = first;
		// 󴴽һָ() helper , Ӧָڵ
		while (true) {
			if (helper.getNext() == first) { // ˵helperָСڵ
				break;
			}
			helper = helper.getNext();
		}
		//Сǰ first   helper ƶ k - 1
		for(int j = 0; j < startNo - 1; j++) {
			first = first.getNext();
			helper = helper.getNext();
		}
		//Сʱfirst  helper ָͬʱ ƶ  m  - 1 , ȻȦ
		//һѭ֪Ȧֻһڵ
		while(true) {
			if(helper == first) { //˵Ȧֻһڵ
				break;
			}
			// first  helper ָͬʱ ƶ countNum - 1
			for(int j = 0; j < countNum - 1; j++) {
				first = first.getNext();
				helper = helper.getNext();
			}
			//ʱfirstָĽڵ㣬ҪȦСڵ
			System.out.printf("С%dȦ\n", first.getNo());
			//ʱfirstָСڵȦ
			first = first.getNext();
			helper.setNext(first); //
			
		}
		System.out.printf("ȦеС%d \n", first.getNo());
		
	}
}

// һBoy࣬ʾһڵ
class Boy {
	private int no;// 
	private Boy next; // ָһڵ,Ĭnull

	public Boy(int no) {
		this.no = no;
	}

	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	public Boy getNext() {
		return next;
	}

	public void setNext(Boy next) {
		this.next = next;
	}

}
